package com.ruoyi.project.jxy.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.UUID;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.jxy.domain.AsrRecord;
import com.ruoyi.project.jxy.domain.DownloadHistory;
import com.ruoyi.project.jxy.service.IDownloadHistoryService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.jxy.domain.TalkingDictRecord;
import com.ruoyi.project.jxy.service.ITalkingDictRecordService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 发音词典Controller
 *
 * @author ruoyi
 * @date 2020-09-09
 */
@RestController
@RequestMapping("/jxy/talkingDictRecord")
public class TalkingDictRecordController extends BaseController {
    @Autowired
    private ITalkingDictRecordService talkingDictRecordService;
    @Autowired
    private IDownloadHistoryService downloadHistoryService;

    /**
     * 查询发音词典列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:talkingDictRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(TalkingDictRecord talkingDictRecord) {
        startPage();
        QueryWrapper<TalkingDictRecord> queryWrapper = new QueryWrapper<TalkingDictRecord>();
        if (StringUtils.isNotBlank(talkingDictRecord.getTheme())) {
            queryWrapper.eq("theme", talkingDictRecord.getTheme());
        }
        if (StringUtils.isNotBlank(talkingDictRecord.getName())) {
            queryWrapper.like("name", talkingDictRecord.getName());
        }
        if (StringUtils.isNotBlank(talkingDictRecord.getSex())) {
            queryWrapper.eq("sex", talkingDictRecord.getSex());
        }
        if (talkingDictRecord.getAge() != null) {
            queryWrapper.eq("age", talkingDictRecord.getAge());
        }
        if (StringUtils.isNotBlank(talkingDictRecord.getContent())) {
            queryWrapper.like("content", talkingDictRecord.getContent());
        }
        List<TalkingDictRecord> list = talkingDictRecordService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 导出发音词典列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:talkingDictRecord:export')")
    @Log(title = "发音词典", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TalkingDictRecord talkingDictRecord) {
        QueryWrapper<TalkingDictRecord> queryWrapper = new QueryWrapper<TalkingDictRecord>(talkingDictRecord);
        List<TalkingDictRecord> list = talkingDictRecordService.list(queryWrapper);
        ExcelUtil<TalkingDictRecord> util = new ExcelUtil<TalkingDictRecord>(TalkingDictRecord.class);
        return util.exportExcel(list, "talkingDictRecord");
    }

    /**
     * 获取发音词典详细信息
     */
    @PreAuthorize("@ss.hasPermi('jxy:talkingDictRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(talkingDictRecordService.getById(id));
    }

    /**
     * 新增发音词典
     */
    @PreAuthorize("@ss.hasPermi('jxy:talkingDictRecord:add')")
    @Log(title = "发音词典", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TalkingDictRecord talkingDictRecord) {
        talkingDictRecord.setCreateTime(new Date());
        talkingDictRecord.setCreateUser(SecurityUtils.getUsername());
        return toAjax(talkingDictRecordService.save(talkingDictRecord) ? 1 : 0);
    }

    /**
     * 修改发音词典
     */
    @PreAuthorize("@ss.hasPermi('jxy:talkingDictRecord:edit')")
    @Log(title = "发音词典", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TalkingDictRecord talkingDictRecord) {
        talkingDictRecord.setUpdateTime(new Date());
        talkingDictRecord.setUpdateUser(SecurityUtils.getUsername());
        return toAjax(talkingDictRecordService.updateById(talkingDictRecord) ? 1 : 0);
    }

    /**
     * 删除发音词典
     */
    @PreAuthorize("@ss.hasPermi('jxy:talkingDictRecord:remove')")
    @Log(title = "发音词典", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(talkingDictRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 导出发音词典数据
     */
    @PreAuthorize("@ss.hasPermi('jxy:talkingDictRecord:zip')")
    @Log(title = "语音识别打包", businessType = BusinessType.OTHER)
    @GetMapping("/zip")
    public AjaxResult zip(TalkingDictRecord talkingDictRecord) {
        QueryWrapper<TalkingDictRecord> queryWrapper = new QueryWrapper<TalkingDictRecord>();
        if (StringUtils.isNotBlank(talkingDictRecord.getTheme())) {
            queryWrapper.eq("theme", talkingDictRecord.getTheme());
        }
        if (StringUtils.isNotBlank(talkingDictRecord.getSex())) {
            queryWrapper.eq("sex", talkingDictRecord.getSex());
        }
        if (StringUtils.isNotBlank(talkingDictRecord.getName())) {
            queryWrapper.like("name", talkingDictRecord.getName());
        }
        if (talkingDictRecord.getAge() != null) {
            queryWrapper.eq("age", talkingDictRecord.getAge());
        }
        if (StringUtils.isNotBlank(talkingDictRecord.getContent())) {
            queryWrapper.like("content", talkingDictRecord.getContent());
        }

        List<TalkingDictRecord> list = talkingDictRecordService.list(queryWrapper);
        DownloadHistory downloadHistory = new DownloadHistory();
        BeanUtil.copyProperties(talkingDictRecord, downloadHistory);
        downloadHistory.setId(null);
        downloadHistory.setType("2");
        downloadHistory.setCreateUser(SecurityUtils.getUsername());
        downloadHistory.setCreateTime(new Date());
        downloadHistoryService.save(downloadHistory);
        ThreadUtil.execute(new Runnable() {
            @Override
            public void run() {
                String baseDir = RuoYiConfig.getProfile();
                //打包的文件夹名称
                String fileName = DateUtils.dateTimeNow();
                String fileDir = baseDir + "/download/" + fileName;
                String wavPath = fileDir + "/wav";
                String txtPath = fileDir + "/txt";
                //新建txt 文件夹
                FileUtil.mkdir(txtPath);
                for (TalkingDictRecord record :
                        list) {
                    //复制文件
                    //每一个文件的真实地址
                    String name = UUID.randomUUID().toString().replace("-", "");
                    //生成txt 文件
                    FileUtil.writeString(record.getContent(), FileUtil.newFile(txtPath + "/" + name + ".txt"), Charset.defaultCharset());
                }
                File zip = ZipUtil.zip(fileDir);
                //压缩包真实名称
                String zipPath = zip.getAbsolutePath();
                String zipName = zip.getName();
                //转换为可下载路径
                String downloadPath = zipPath.replace(baseDir, "/profile");
                downloadHistory.setPath(downloadPath);
                downloadHistory.setDisplayName(zipName);
                downloadHistoryService.updateById(downloadHistory);
            }
        });
        return AjaxResult.success();
    }
}
